package com.zxy.employee.excel;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxy.base.BusinessException;
import com.zxy.employee.entity.EmployeeEntity;
import com.zxy.employee.mapper.EmployeeMapper;
import com.zxy.employee.service.EmployeeService;

import java.util.List;

public class UploadEmployeeListener implements ReadListener<EmployeeData> {


    private EmployeeService employeeService;

    private String result="";

    private StringBuilder resultBuilder = new StringBuilder("");

    private static final int BATCH_COUNT = 100;

    private List<EmployeeData> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);



    public UploadEmployeeListener(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @Override
    public void invoke(EmployeeData employeeEntity, AnalysisContext analysisContext)  {
        cachedDataList.add(employeeEntity);

        if (cachedDataList.size() > BATCH_COUNT) {
            try {
                this.onException(new BusinessException("每次最多导入100条！"),analysisContext);
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

        List<EmployeeEntity> employeeEntities = BeanUtil.copyToList(cachedDataList, EmployeeEntity.class);

        for(EmployeeEntity e: employeeEntities) {
            boolean phoneExists = employeeService.getBaseMapper().exists(new QueryWrapper<EmployeeEntity>().lambda()
                    .eq(EmployeeEntity::getPhone, e.getPhone()));
            boolean idCard = employeeService.getBaseMapper().exists(new QueryWrapper<EmployeeEntity>().lambda()
                    .eq(EmployeeEntity::getIdCard, e.getIdCard()));
            if(phoneExists) {
                continue;
            }
            if(idCard) {
                continue;
            }

            employeeService.save(e);
        }
        cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        if(exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException convertException = (ExcelDataConvertException) exception;

            String errMsg = String.format("第 %d 行 ，第 % 列 数据格式转换错误 \n",
                    convertException.getRowIndex(),convertException.getColumnIndex());
            this.resultBuilder.append(errMsg);

        } else {
            throw exception;
        }

    }

    public String getResult() {
        this.result =this.resultBuilder.toString();
        return result;
    }
}
